package ro.unibuc.nautilus.service;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import ro.unibuc.nautilus.dao.GenericDAO;
import ro.unibuc.nautilus.domain.Route;
import ro.unibuc.nautilus.domain.Ship;

public class ShipsServiceImpl implements ShipsService {

	private GenericDAO<Ship, Long> shipsDAO;

	public Ship findShip(Long id) {
		Ship ship = shipsDAO.find(id);
		if (ship != null) {
			ship.setCurrentRoute(findCurrentRoute(ship.getRoutes()));
		}
		return ship;
	}

	public List<Ship> findAll() {
		List<Ship> ships = shipsDAO.findAll();
		for (int i = 0; i < ships.size(); i++) {
			Ship ship = ships.get(i);
			ship.setCurrentRoute(findCurrentRoute(ship.getRoutes()));
		}
		return ships;
	}

	/**
	 * Find the eventual route on which the ship is on
	 * 
	 * @param routes
	 * @return
	 */
	private Route findCurrentRoute(Set<Route> routes) {
		Date today = Calendar.getInstance().getTime();
		for (Iterator<Route> it = routes.iterator(); it.hasNext();) {
			Route route = it.next();
			// if not arrived yet
			if (route.getArrivalDate() == null) {
				return route;
			} else if (route.getDepartureDate().getTime() <= today.getTime()
					&& today.getTime() <= route.getArrivalDate().getTime()) {
				return route;
			}
		}
		return null;
	}

	public void createOrUpdate(Ship ship) {
		if (ship.getId() == 0) {
			shipsDAO.create(ship);
		} else {
			shipsDAO.update(ship);
		}
	}

	public void setShipsDAO(GenericDAO<Ship, Long> shipsDAO) {
		this.shipsDAO = shipsDAO;
	}
}
